package com.example.ch3_3.controller;

import com.example.ch3_3.entity.User;
import com.example.ch3_3.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
public class IndexController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = {"/index1", "/main"})
    public String index() {
        log.info("访问主页");
        return "forward:/index.html"; // 假设你的主页视图名为 index
    }

    // 访问登录页面
    @RequestMapping(value = "/login1")
    public String login() {
        log.info("访问登录页面");
        return "login"; // 返回视图名称
    }

    @RequestMapping(value = "/userlogin1", method = RequestMethod.POST)
    @ResponseBody
    public User userlogin(User user) {
        log.info("用户尝试登录: {}", user);
        log.info("正在进行登录验证");
        if (loginService.login(user.getUsername(), user.getPassword())) {
            log.info("登录成功");
            return user;
        } else {
            log.info("登录失败");
            return new User(); // 返回一个新的空用户对象表示登录失败
        }
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showregister() {
        return "register"; // 返回视图名称
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String handleregister(User user, Model model) {
        try {
            loginService.registerUser(user);
            model.addAttribute("success", "注册成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            model.addAttribute("error", "注册失败");
        }
        return "register"; // 返回视图名称
    }
}